package org.demo.serv;

import java.io.*;
import java.net.Socket;

/**
 * Created by tangwy on 2016/7/8.
 */
public class ServerThread implements  Runnable {
    private Socket socket;
    private PrintWriter out;
    private BufferedReader br;
    public ServerThread(Socket socket){
        this.socket=socket;
        //init();

    }

    private void init(){
        try {
            this.out=new PrintWriter(socket.getOutputStream());
            this.br=new BufferedReader(new InputStreamReader(socket.getInputStream()));
            send("连接服务器成功!");
        }catch (IOException e){
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        try {
            br = new BufferedReader(new InputStreamReader(
                    socket.getInputStream()));
            out = new PrintWriter(socket.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
        send("连接服务器成功!");
      while (true){
           receive();
       }
       /* try {
            BufferedReader in = new BufferedReader(new InputStreamReader(
                    socket.getInputStream()));
            PrintWriter out = new PrintWriter(socket.getOutputStream());
            // Mutil User but can't parallel

            while (true) {
                String str = in.readLine();
                System.out.println(str);
                out.println("has receive....");
                out.flush();
                if (str.equals("end"))
                    break;
            }
            socket.close();
        } catch (IOException ex) {
        } finally {
        }*/
    }

    private void send(String msg){
        this.out.println(msg);
    }

    private void receive(){
        try {
            String msg=this.br.readLine();
            /*if (msg==null||"".equals(msg)){
                return;
            }*/
            System.out.println(msg);
            //业务处理
            String retMsg="服务器数据";
            if ("1".equals(msg)){
                retMsg+="1";
            }
            send(retMsg);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
